<template>
  <div>
    <el-dialog v-if="load" :title="title" v-model="visible" align-center width="720px" @close="handleClose" :close-on-click-modal="false">
      <el-form :model="formData" label-width="160px" :rules="rules" ref="ruleFormRef" class="formw200">
        <el-form-item label="费用类型:" prop="fee_type">
          <el-select class="input" v-model="formData.fee_type" clearable placeholder="费用类型">
            <el-option-group v-for="group in freeType" :key="group.label" :label="group.label">
              <el-option v-for="item in group.options" :key="item.value" :label="item.label" :value="item.value" />
            </el-option-group>
          </el-select>
        </el-form-item>
        <el-form-item label="费用说明:" prop="fee_description">
          <el-input class="input" v-model="formData.fee_description" placeholder="费用说明"></el-input>
        </el-form-item>
        <el-form-item label="优先级:">
          <el-input class="input" v-model="formData.priority" placeholder="优先级"></el-input>
        </el-form-item>

        <el-form-item label="订单发货类型:" prop="order_shipping_type">
          <el-select v-model="formData.order_shipping_type" class="input" collapse-tags clearable placeholder="订单发货类型">
            <el-option v-for="(d, i) in orderShippingType" :key="i" :label="d.label" :value="d.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发货仓库:" prop="shipping_type">
          <el-radio-group v-model="formData.shipping_type" @change="changeType">
            <el-radio :label="0" size="large">按仓库名称</el-radio>
            <el-radio :label="1" size="large">按仓库类型</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="">
          <div class="input" v-show="formData.shipping_type === 0">
            <WarehouseSelect v-model="formData.shipping_warehouse_id" collapse-tags clearable :multiple="true" placeholder="发货仓库" @change="changeWarehouse" />
          </div>
          <el-select v-show="formData.shipping_type === 1" v-model="formData.warehouse_type" clearable class="input" collapse-tags placeholder="仓库类型">
            <el-option v-for="(d, i) in originOption.warehouseOpt" :key="i" :label="d.label" :value="d.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="平台:" prop="platform_id">
          <el-select v-model="formData.platform_id" class="input" collapse-tags placeholder="平台" @change="changePlatform" clearable>
            <!-- <el-option v-for="(d, i) in platformList" :key="i" :label="d.label" :value="Number(d.value)"></el-option> -->
            <el-option v-for="(d, i) in platformList" :key="i" :label="d.platform_name" :value="Number(d.platform_id)"></el-option>
          </el-select>

          <!-- <VSelect v-model="formData.platform_id" placeholder="店铺" clearable collapse-tags confusedPaste :paste="true" :options="platformList" @change="changePlatform" class="w-[300px]" multiple>
          </VSelect> -->
        </el-form-item>
        <el-form-item label="站点:">
          <!-- <el-select v-model="formData.site_id" class="input" multiple collapse-tags clearable placeholder="站点" @change="changeSite">
            <el-option v-for="(d, i) in siteList" :key="i" :label="d.site_abbrev" :value="d.site_id"></el-option>
          </el-select> -->
          <VSelect v-model="formData.site_id" placeholder="站点" clearable collapse-tags confusedPaste :paste="true" :options="siteList" @change="changeSite" class="input" multiple></VSelect>

          <el-button type="primary" class="ml-4" @click="checkAllSite">全选</el-button>
        </el-form-item>
        <el-form-item label="店铺:">
          <!-- <el-select v-model="formData.shop_id" class="input" multiple collapse-tags clearable placeholder="店铺">
            <el-option v-for="(d, i) in shopList" :key="i" :label="d.shop_name" :value="d.shop_id"></el-option>
          </el-select> -->
          <VSelect v-model="formData.shop_id" placeholder="店铺" clearable collapse-tags confusedPaste :paste="true" :options="shopList" class="input" multiple @change="aaaaa"></VSelect>

          <el-button type="primary" class="ml-4" @click="checkAllShop">全选</el-button>
        </el-form-item>
        <el-form-item label="SKU:">
          <div class="input">
            <el-button type="primary" @click="showSKU">添加</el-button>
          </div>
          <div class="skuBox">
            <p v-for="(item, index) in formData.sku" :key="index">
              {{ item }}

              <svg-icon icon-class="close_red" @click="delSku(index)" />
            </p>
          </div>
        </el-form-item>
        <el-form-item label="计费方式:">
          <el-radio-group v-model="formData.billing_method">
            <el-radio :label="0" size="large">按产品个数</el-radio>
            <el-radio :label="1" size="large">按包裹个数（订单个量）</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="费用规则:" v-if="formData.billing_method == 0">
          <div class="expenseRule">
            <div class="flex mb-2">
              <el-button type="primary">设置费用上限</el-button>
              <div class="flex"><span class="ml-2">最高：</span> <el-input style="width: 100px" v-model="formData.maximum_fee" type="number"></el-input><span class="ml-2">RMB</span></div>
            </div>
            <el-table :data="formData.fee_rules" style="width: 100%" border>
              <el-table-column prop="date" label="数量区间" width="220">
                <template #default="scope">
                  <el-input v-model="scope.row.range_min" style="width: 85px" type="Number"></el-input> <span>-</span>
                  <el-input v-model="scope.row.range_max" style="width: 85px" type="Number"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="name" label="费用单价/RMB" width="150">
                <template #default="scope">
                  <el-input v-model="scope.row.fee_unit_price" oninput="value=value.replace(/[^\d.]/g, '').replace(/(\.\d{3}).+/, '$1').replace(/(\.\d{2})\d+/, '$1')"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template #default="{ row, column, $index }">
                  <el-button size="small" type="danger" @click="delRule($index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="mt-2"><el-button icon="plus" @click="addRule">添加</el-button></div>
            <div>说明：例如：设置区间数量1~5，单价为3元，区间数量6~10时，单价为2元，若订单产品总数为9个，根据公式，总费用5*3+（9-5）*2=23元</div>
          </div>
        </el-form-item>

        <el-form-item label="费用规则:" v-if="formData.billing_method == 1">
          <div class="expenseRule">
            <el-form-item label="费用单价:">
              <el-input class="input mb-3" v-model="formData.fee_unit_price" oninput="value=value.replace(/^(\d{1,3}(\.\d{0,2})?).*/, '$1');"></el-input><span class="ml-2">RMB</span>
            </el-form-item>
            <el-form-item label="分摊规则:">
              <el-select v-model="formData.sharing_rule" class="input" collapse-tags clearable placeholder="平台">
                <el-option v-for="(d, i) in sharingRules" :key="i" :label="d.label" :value="d.value"></el-option>
              </el-select>
            </el-form-item>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <!-- <div class="flex justify-center py-2"> -->
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" :loading="loadings.submit" @click="submit">保 存</el-button>
        <!-- </div> -->
      </template>
    </el-dialog>
    <SelectProduct v-model:visible="visibleProductSku" :multiple="true" :selectIds="formData.sku" @uploadSku="handleProductSku"> </SelectProduct>
  </div>
</template>

<script setup>
import { nextTick, reactive, toRefs } from "vue"
import { detail, createCost, updateCost } from "../api"
import { ElMessage } from "element-plus"
import WarehouseSelect from "@/components/WarehouseSelect/index.vue"
import { getPlatformOptions, getSiteOptions, getShopOptions, getWarehouseEnum } from "@/api/public"
import SelectProduct from "@/components/SelectProduct"
const aaaaa = () => {
  nextTick(() => {
    console.log(formData.value.shop_id)
  })
}
import XEUtils from "xe-utils"
const ruleFormRef = ref()
const load = ref(false)
const visible = ref(false)
let loadings = reactive({})
// 声明接收参数
const props = defineProps({
  title: {
    type: String,
    default: "新增",
  },
  sharingRules: {
    type: Array,
    default: [],
  },
  orderShippingType: {
    type: Array,
    default: [],
  },
  freeType: {
    type: Array,
    default: [],
  },
  originOption: {
    type: Object,
    default: () => {},
  },
})
const data = reactive({
  formData: {
    priority: 0,
    shipping_type: 0,
    platform: "",
    fee_rules: [],
    billing_method: 0,
    sku: [],
  },
  isType: false,
  platformList: [],
  siteList: [],
  shopList: [],
  warehouseEnum: [], // 仓库属性
})
const { formData, isType, platformList, siteList, shopList, warehouseEnum } = toRefs(data)
const { title, billingMethod, orderShippingType, freeType } = toRefs(props)
const emit = defineEmits(["close", "confirm"])
//添加费用规则
const addRule = () => {
  formData.value.fee_rules.push({
    fee_unit_price: null,
    range_max: null,
    range_min: null,
  })
}
//删除费用规则
const delRule = (index) => {
  formData.value.fee_rules.splice(index, 1)
}
//删除sku
const delSku = (index) => {
  formData.value.sku.splice(index, 1)
}
const rules = reactive({
  fee_type: [{ required: true, message: "请选择", trigger: "change" }],
  fee_description: [{ required: true, message: "不能为空", trigger: "blur" }],
  order_shipping_type: [{ required: true, message: "请选择", trigger: "change" }],
  shipping_type: [{ required: true, message: "请选择", trigger: "change" }],
  shipping_warehouse_id: [{ required: true, message: "请选择", trigger: "change" }],
  platform_id: [{ required: true, message: "请选择", trigger: "change" }],
})

// 打开弹窗
const open = (row = {}) => {
  if (!load.value) {
    load.value = true
  }
  if (row.id) {
    isType.value = true
    detail({ id: row.id }).then((res) => {
      loadings = reactive({})
      getSite(res.data.platform_id)
      getShop(res.data.platform_id, res.data.site_id)
      res.data.order_shipping_type = res.data.order_shipping_type || ""
      let shipping_warehouse_id = res.data.shipping_warehouse_id
      formData.value = res.data
      nextTick(() => {
        formData.value.shipping_warehouse_id = shipping_warehouse_id
      })
      visible.value = true
    })
  } else {
    loadings = reactive({})
    isType.value = false
    visible.value = true
  }
}
// 关闭弹窗
const close = () => {
  formData.value = { fee_rules: [] }
  ruleFormRef.value.resetFields()
  visible.value = false
}

const handleClose = () => {
  close()
  emit("close")
}
// 提交
const submit = () => {
  let { validate } = ruleFormRef.value
  validate((valid) => {
    if (valid) {
      loadings.submit = true
      const {
        id,
        fee_type,
        fee_description,
        priority,
        order_shipping_type,
        shipping_type,
        shipping_warehouse_id,
        warehouse_type,
        shipping_warehouse,
        platform_id,
        site_id,
        shop_id,
        sku,
        billing_method,
        fee_unit_price,
        fee_rules,
        maximum_fee,
        sharing_rule,
      } = formData.value
      fee_rules.map((e) => {
        e.range_max = e.range_max ? Number(e.range_max) : null
        e.fee_unit_price = e.fee_unit_price ? Number(e.fee_unit_price) : null
        e.range_min = e.range_min ? Number(e.range_min) : null
      })
      // if(typeof shipping_warehouse_id == 'string'){
      //   console.log(shipping_warehouse_id);
      //   shipping_warehouse_id = [ shipping_warehouse_id ]
      //  }
      if (isType.value) {
        updateCost({
          id,
          fee_type,
          fee_description,
          priority,
          order_shipping_type,
          shipping_type,
          shipping_warehouse_id,
          warehouse_type,
          shipping_warehouse,
          platform_id,
          site_id,
          shop_id,
          sku,
          billing_method,
          fee_unit_price,
          fee_rules,
          maximum_fee,
          sharing_rule,
        })
          .then((res) => {
            ElMessage({ message: "保存成功！", type: "success" })
            emit("confirm")
            close()
          })
          .finally(() => {
            loadings.submit = false
          })
      } else {
        createCost({
          fee_type,
          fee_description,
          priority,
          order_shipping_type,
          shipping_type,
          shipping_warehouse_id,
          warehouse_type,
          shipping_warehouse,
          platform_id,
          site_id,
          shop_id,
          sku,
          billing_method,
          fee_unit_price,
          fee_rules,
          maximum_fee,
          sharing_rule,
        })
          .then((res) => {
            ElMessage({ message: "保存成功！", type: "success" })
            emit("confirm")
            close()
          })
          .finally(() => {
            loadings.submit = false
          })
      }
    }
  })
}
const getWarehouseEnumList = async () => {
  try {
    const res = await getWarehouseEnum()
    warehouseEnum.value = res.data.wms_attribute
  } catch (e) {
    throw Error(e)
  }
}
// 获取平台
const getPlatform = async () => {
  try {
    const res = await getPlatformOptions()

    // platformList.value = res.data?.map((v) => ({ label: v.platform_name, value: Number(v.platform_id) }))
    platformList.value = res.data
  } catch (e) {
    throw Error(e)
  }
}
// 选择平台
const changePlatform = async (val) => {
  siteList.value = []
  shopList.value = []
  formData.value.site_id = ""
  formData.value.shop_id = ""
  getSite(val)
}
// 获取站点
const getSite = async (id) => {
  try {
    const res = await getSiteOptions({
      platform_ids: [id],
    })
    // siteList.value = res.data
    siteList.value = res.data?.map((v) => ({ label: v.site_abbrev, value: v.site_id }))
  } catch (e) {
    throw Error(e)
  }
}
// 选择站点
const changeSite = async (val) => {
  shopList.value = []
  formData.value.shop_id = ""
  getShop(formData.value.platform_id, val)
}
// 获取店铺列表
const getShop = async (platform_id, site_ids) => {
  try {
    const res = await getShopOptions({
      site_ids,
      platform_ids: [platform_id],
    })
    // shopList.value = res.data
    shopList.value = res.data?.map((v) => ({ label: v.shop_name, value: v.shop_id }))
  } catch (e) {
    throw Error(e)
  }
}
// 全选站点
const checkAllSite = async () => {
  if (siteList.value.length == 0) {
    ElMessage.error("站点列表为空")
    return
  }
  // const site_ids = siteList.value.map((i) => i.site_id)
  // formData.value.site_id = site_ids
  // getShop(formData.value.platform_id, site_ids)
  const site_ids = siteList.value.map((i) => i.value)
  formData.value.site_id = site_ids
  getShop(formData.value.platform_id, site_ids)
}
// 全选店铺
const checkAllShop = async () => {
  if (shopList.value.length == 0) {
    ElMessage.error("店铺列表为空")
    return
  }
  // const shop_ids = shopList.value.map((i) => i.shop_id)
  // formData.value.shop_id = shop_ids
  const shop_ids = shopList.value.map((i) => i.value)
  formData.value.shop_id = shop_ids
}

const visibleProductSku = ref(false)
const showSKU = async () => {
  visibleProductSku.value = true
}
const handleProductSku = async (list) => {
  formData.value.sku = [...formData.value.sku, ...list.map((i) => i.sku)]
}
const changeType = async (val) => {
  if (val == 0) {
    formData.value.warehouse_type = ""
  } else {
    formData.value.shipping_warehouse_id = ""
    formData.value.shipping_warehouse = ""
  }
}
const changeWarehouse = async (val) => {
  formData.value.shipping_warehouse = val
}
onMounted(() => {
  getWarehouseEnumList()
  getPlatform()
})
defineExpose({ open })
</script>
<style lang="scss" scoped>
.formw200 {
  :deep(.input) {
    width: 300px;
  }
}
:deep(.el-radio.el-radio--large) {
  height: initial;
}
.skuBox {
  width: 300px;
  min-height: 100px;
  border: 1px solid  var(--base-border-color);
  border-radius: 5px;
  margin-top: 10px;
  padding: 5px 10px;
  max-height: 300px;
  overflow: auto;
  cursor: pointer;
  p {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
.expenseRule {
  box-sizing: content-box;
  min-height: 100px;
  border: 1px solid  var(--base-border-color);
  border-radius: 5px;
  // margin-top: 10px;
  padding: 10px 15px;
  :deep(label) {
    width: 80px !important;
  }
}
:deep(input::-webkit-outer-spin-button),
:deep(input::-webkit-inner-spin-button) {
  -webkit-appearance: none !important;
}
:deep(.el-input__inner) {
  line-height: 1px !important;
}
</style>
